<?php

namespace app\user\logic;

use app\common\exception\LogicException;
use app\common\logic\EncryptLogic;
use app\common\logic\PhoneCodeLogic;
use app\common\logic\RandCreateStrLogic;
use app\model\Barn;
use app\model\Fence;
use app\model\Pig;
use app\model\User;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class UserLogic
{
    /**
     * @Description 获取登录用户信息
     * @return array
     * @throws DbException
     * @time 2023/08/31 14:20:47
     * @author: zj
     */
    public function getUserInfo()
    {
        $headToken = request()->header("token");
        if (!$headToken) {
            throw new LogicException("登录已过期，请重新登录",4101);
        }
        $tokenData = cache()->get('user_'. $headToken);
        if (!$tokenData) {
            throw new LogicException("登录已过期，请重新登录",4101);
        }

        cache()->set('user_'.$headToken, $tokenData, 86400);

        return  json_decode($tokenData, true);
    }

    /**
     * @Description 修改密码
     * @author: zj
     * @param int $userId
     * @param string $oldPwd
     * @param string $newPwd
     * @time 2023/09/09 17:50:05
     * @return true
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function changePassword(int $userId, string $oldPwd, string $newPwd)
    {
        $userModel = new User();
        $userInfo = $userModel->field('password,salt')
            ->where('id', $userId)
            ->where('delete_time', $userModel::IS_DELETE_NO)
            ->find();

        if (!$userInfo) {
            throw new LogicException('用户不存在');
        }

        $encrypt = new EncryptLogic();
        $oldPwdMd5 = $encrypt->encryptMD5($oldPwd, $userInfo['salt']);
        if ($oldPwdMd5 != $userInfo['password']) {
            throw new LogicException('旧密码错误');
        }

        $randLogic = new RandCreateStrLogic();
        $salt = $randLogic->create(4);
        $newPwdMd5 = $encrypt->encryptMD5($newPwd, $salt);

        $userModel->where('id', $userId)
            ->update([
                'password' => $newPwdMd5,
                'salt' => $salt,
                'update_time' => request()->time()
            ]);

        return true;
    }

    /**
     * @Description 用户详情
     * @param string $token
     * @param int $factoryId
     * @return array
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @time 2023/09/11 15:23:26
     * @author: zj
     */
    public function detail(string $token,int $factoryId)
    {
        $model = new User();
        $info = $model->alias('u')
            ->join('user_token ut','u.id = ut.user_id','left')
            ->field('u.id,u.name,u.phone,u.company,u.address,u.province,u.city,u.district,u.create_time')
            ->where('ut.token',$token)
            ->where('u.status',$model::STATUS_ENABLE)
            ->where('u.delete_time',$model::IS_DELETE_NO)
            ->find();
        if (!$info) {
            throw new LogicException("用户不存在");
        }
        $info = $info->toArray();
        $info['full_address'] = $info['province'].$info['city'].$info['district'].$info['address'];
        // 总栋数
        $barnModel = new Barn();
        $barnTotal = $barnModel->checkBarnCount($factoryId);
        $info['building_total'] = $barnTotal;
        // 总栏数
        $fenceModel = new Fence();
        $fenceTotal = $fenceModel->checkFenceCount($factoryId);
        $info['fence_total'] = $fenceTotal;
        // 总猪数
        $pigModel = new Pig();
        $pigTotal = $pigModel->checkPigCount($factoryId);
        $info['pig_total'] = $pigTotal;

        return $info;
    }

    /**
     * @Description 修改个人信息
     * @param array $param
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @time 2023/09/11 16:00:11
     * @author: zj
     */
    public function changeUserInfo(array $param)
    {
        $userId = request()->user_info['user_id'];
        $model = new User();
        $info = $model->field('id')
            ->where('id',$userId)
            ->find();
        if (!$info) {
            throw new LogicException("数据不存在");
        }

        if ($model->checkPhoneIsExist($param['phone'],$userId)) {
            throw new LogicException("手机号码已注册");
        }

        if ($model->checkNameIsExist($param['name'],$userId)) {
            throw new LogicException("用户名已存在");
        }

        $model->where('id',$userId)
            ->update([
                'name' => $param['name'],
                'phone' => $param['phone'],
                'company' => $param['company'],
                'province' => $param['province'],
                'city' => $param['city'],
                'district' => $param['district'],
                'address' => $param['address']
            ]);
    }

    /**
     * @Description 找回密码
     * @author: zj
     * @param string $phone
     * @param string $code
     * @param string $new_password
     * @time 2024/03/04 17:25:51
     * @return true
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function findPassword(string $phone,string $code,string $new_password)
    {
        $logic = new PhoneCodeLogic();
        // 判断手机验证码
//        $logic->checkCode($phone,$code);

        $userModel = new User();
        $userInfo = $userModel->field('id,password,salt')
            ->where('phone', $phone)
            ->where('delete_time', $userModel::IS_DELETE_NO)
            ->find();

        if (!$userInfo) {
            throw new LogicException('用户不存在');
        }

        $randLogic = new RandCreateStrLogic();
        $salt = $randLogic->create(4);

        $encrypt = new EncryptLogic();
        $newPwdMd5 = $encrypt->encryptMD5($new_password, $salt);

        $userModel->where('id',$userInfo['id'])
            ->update([
                'salt' => $salt,
                'password' => $newPwdMd5,
                'update_time' => request()->time()
            ]);

        return true;
    }

    /**
     * @Description 设置缓存
     * @author: zj
     * @param string $token
     * @param array $userInfo
     * @time 2023/08/29 10:02:25
     * @return true
     */
    public function setCache(string $token,array $userInfo)
    {
        cache()->set('user_'.$token,json_encode($userInfo,JSON_UNESCAPED_UNICODE),86400);

        return true;
    }
}